package com.youths.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.youths.domain.*;
import com.youths.response.Result;
import com.youths.service.*;
import com.youths.util.EnDecoderUtil;
import com.youths.util.ResultEnum;
import com.youths.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/7/6
 */
@Controller
@RequestMapping(value = "/")
public class RecognizationController {
    @Autowired
    RecognizationService recognizationService;

    @Autowired
    SliceService sliceService;

    @Autowired
    YouthInfoService youthInfoService;

    @Autowired
    ScoreService scoreService;

    @Autowired
    HeightInfoService heightInfoService;

    @Value("${des.key}")
    String key;

    @GetMapping(value = "resultNone")
    private String resultJs() {
        return "analysis/result";
    }

    @GetMapping(value = "report")
    @ResponseBody
    public String report(@RequestParam("sliceId") String sliceId) {
        //传入sliceId -> youthId  recoId  heightId scoreId
        Report report = getReport(sliceId, null);
        if (report != null) {
            return JSONObject.toJSONString(report);
        }
        return null;
    }

    @GetMapping(value = "result")
    public String result(@RequestParam("sliceId") String sliceId,
                         Model model) {
        //传入sliceId -> youthId  recoId  heightId scoreId
        Report report = getReport(sliceId.replaceAll(" ", "+"), model);
        if (report != null) {
            model.addAttribute("report", report);
            model.addAttribute("sliceStr", sliceId);
        }
        return "analysis/result";
    }

    //return param youthId sliceId recoId heightId
    @PostMapping(value = "analysis", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String analysis(@RequestParam("height") Float height,
                           @RequestParam("weight") Float weight,
                           @RequestParam("youthId") Integer youthId,
                           @RequestParam("sliceId") String sliceId,
                           @RequestParam("time") String time) {
        Gson gson = new Gson();
        Map<String, Object> resMap = new HashMap<>();
        try {
            byte[] byteStr = Base64.getDecoder().decode(sliceId.replaceAll(" ", "+"));
            byte[] decode_bytes = EnDecoderUtil.DESDecrypt(key, byteStr);
            Integer sliceIdInt = Integer.parseInt(new String(decode_bytes));

            Slice slice = sliceService.query(sliceIdInt);
            if (slice.getPhysicalTime() == null) {
                //update
                SimpleDateFormat sdf = new SimpleDateFormat("mm/DD/yyyy");
                Date checkTime = sdf.parse(time);
                int updateCode = sliceService.updateTime(sliceIdInt, checkTime);
                //System.out.println("【time】" + time + "【】" +checkTime);
            }

            ResultEnum resultEnum = recognizationService.analysisProcess(sliceIdInt, height, weight, youthId);
            if (resultEnum.getCode() == 200) {
                resMap.put("code", 1);
            }else {
                resMap.put("code" , 0);
                resMap.put("msg", resultEnum.getMessage());
            }
        }catch (Exception e){
            resMap.put("code" , 0);
            e.printStackTrace();
        }
        return gson.toJson(resMap);
    }

    private Report getReport(String sliceId, Model model) {
        try {
            int type = 1;
            byte[] byteStr = Base64.getDecoder().decode(sliceId);
            byte[] decode_bytes = EnDecoderUtil.DESDecrypt(key, byteStr);
            Integer sliceIdInt = Integer.parseInt(new String(decode_bytes));
            Report report = new Report();
            Slice slice = sliceService.query(sliceIdInt);
            if (slice != null) {
                if (slice.getState() >= 4) {
                    type = 2;
                }
                report.setWeight(slice.getWeight());
                report.setHeight(slice.getHeight());
                report.setCheckDate(slice.getPhysicalTime());
                Integer youthId = slice.getYouthId();
                YouthInfo youthInfo = youthInfoService.queryYouthInfo(youthId);
                List<Recognization> recoList = new ArrayList<>();
                recoList = recognizationService.getRecogList(sliceIdInt);
                if (youthInfo != null && recoList.size() > 0) {
                    String sexArray[] = {"男", "女"};
                    report.setName(youthInfo.getYouthName());
                    report.setSex(sexArray[youthInfo.getYouthSex()]);
                    report.setBirth(youthInfo.getYouthBirth());
                    report.setSliceId(StringUtil.encryption(slice.getSlicingId()));
                    report.setAge(StringUtil.getAge(youthInfo.getYouthBirth(), slice.getPhysicalTime()));
                    report.setState(slice.getState());
                    for (Recognization recognization : recoList) {
                        Integer recoId = recognization.getRecoId();
                        Score score = scoreService.queryScore(recoId);
                        HeightInfo heightInfo = heightInfoService.query(recoId);
                        List<List<Float>> point = new ArrayList<>();
                        point = StringUtil.stringToArray(heightInfo!=null?heightInfo.getGrowthTrend():null);
                        //recog kind=1 ai kind=2 expert
                        if (recognization.getKind() == type) {
                            report.setChnBoneAge(score.getChnBoneage());
                            report.setTw3BoneAge(score.getTw3Boneage());
                            report.setTwcBoneAge(score.getTwcBoneage());
                            report.getCurveChn().setBp(heightInfo!=null?heightInfo.getBpForecastHeight():null);
                            report.getCurveChn().setBp2(heightInfo!=null?heightInfo.getImproveBpForecastHeight():null);
                            report.getCurveChn().setTarget(heightInfo!=null?heightInfo.getGeneticHeight():null);
                            report.getCurveChn().setPoints(point);
                            report.getCurveChn().setHeightEvaluate(heightInfo!=null?heightInfo.getEvaluate():null);//身高评价
                            report.setWholeAgeGrowth(score.getSituation());//骨龄评价
                            report.setExpertSuggest(score.getSuggestion());//专家建议
                            if (model != null) {
                                model.addAttribute("recogStr", StringUtil.encryption(recognization.getRecoId()));
                            }
                        }
                    }
                    return report;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/back/getRecoList")
    @ResponseBody
    public Result getRecoList(@RequestParam("pageNum") Integer pageNum,
                              @RequestParam("type") Integer type,
                              @RequestParam("date1") String date1,
                              @RequestParam("date2") String date2,
                              @RequestParam("recoId") Integer recoId,
                              @RequestParam("slicingId") Integer slicingId,
                              @RequestParam("card") String card){
        return Result.success(recognizationService.getRecoList(pageNum,type,date1,date2,recoId,slicingId,card));
    }

    @GetMapping("/back/getRecoDetail")
    @ResponseBody
    public Result getRecoDetail(@RequestParam("recoId") Integer recoId,
                                @RequestParam("slicingId") Integer slicingId){
        return Result.success(recognizationService.getRecoDetail(recoId,slicingId));
    }

}
